package com.fgba.express.security;


import com.fasterxml.jackson.databind.ObjectMapper;

import com.fgba.express.comm.GlobalConst;
import com.fgba.express.comm.result.Result;
import com.fgba.express.util.BeanContextUtil;
import com.fgba.express.util.JwtUtils;
import com.fgba.express.util.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.Principal;

/**
 * @author fgba
 */
@Component
public class LogoutHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
            Principal principal = (Principal) authentication.getPrincipal();
            BeanContextUtil.getBean(RedisUtil.class).del(GlobalConst.GRANTED_AUTHORITY + principal.getName());
        }

        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader(BeanContextUtil.getBean(JwtUtils.class).getHeader(), "");

        Result<Object> result = Result.success();

        outputStream.write(new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
